/*
 * Copyright 2009 Jinbo Lin. All rights reserved.
 * 
 * cn.edu.pku.dao.impl HumanResourcesManagementSystem
 *
 * Created on 2009-12-20
 */
package cn.edu.pku.dao.impl;

import java.io.Serializable;
import java.util.List;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import cn.edu.pku.dao.TitleDao;
import cn.edu.pku.model.Title;

/**
 * @author Jinbo Lin
 * 
 * 
 */
public class TitleDaoHibernate extends HibernateDaoSupport implements TitleDao {

	/*
	 * (non-Javadoc)
	 * 
	 * @see cn.edu.pku.dao.TitleDao#delete(int)
	 */
	@Override
	public void delete(int id) {
		if (null != this.get(id)) {
			this.getHibernateTemplate().delete(
					this.getHibernateTemplate().get(Title.class, id));
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see cn.edu.pku.dao.TitleDao#delete(cn.edu.pku.model.Title)
	 */
	@Override
	public void delete(Title title) {
		if (null != this.get(title.getTitleId())) {
			this.getHibernateTemplate().delete(title);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see cn.edu.pku.dao.TitleDao#findAll()
	 */
	@SuppressWarnings("unchecked")
	@Override
	public List<Title> findAll() {
		String hql = "from Title title where title.salaryStandardId!=0";
		return this.getHibernateTemplate().find(hql);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see cn.edu.pku.dao.TitleDao#findTitleIdByTitleName(java.lang.String)
	 */
	@SuppressWarnings("unchecked")
	@Override
	public int findTitleIdByTitleName(String titleName) {
		String hql = "select title.titleId from Title title "
				+ "where title.titleName=?";
		List<Integer> titleIds = this.getHibernateTemplate().find(hql,
				titleName);
		int titleId = (null != titleIds && 0 != titleIds.size()) ? titleIds
				.get(0).intValue() : 0;
		return titleId;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see cn.edu.pku.dao.TitleDao#get(int)
	 */
	@SuppressWarnings("unchecked")
	@Override
	public Title get(int id) {
		String hql = "from Title title where title.titleId=? and "
				+ "title.salaryStandardId!=0";
		List<Title> titles = this.getHibernateTemplate().find(hql,
				new Integer(id));
		Title title = (null != titles && 0 != titles.size()) ? titles.get(0)
				: null;
		return title;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see cn.edu.pku.dao.TitleDao#save(cn.edu.pku.model.Title)
	 */
	@Override
	public Serializable save(Title title) {
		if (0 == this.findTitleIdByTitleName(title.getTitleName())) {
			this.getHibernateTemplate().save(title);
			title.setTitleId(this.findTitleIdByTitleName(title.getTitleName()));
		} else {
			title = null;
		}
		return title;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see cn.edu.pku.dao.TitleDao#update(cn.edu.pku.model.Title)
	 */
	@Override
	public void update(Title title) {
		if (null != this.get(title.getTitleId())) {
			// this.getHibernateTemplate().saveOrUpdate(title);
			this.getHibernateTemplate().update(title);
		}
	}

}
